package gwtappcontainer.server.apis.insight;

import static gwtappcontainer.server.apis.insight.OfyService.ofy;
import gwtappcontainer.server.DatastoreNamespaces;
import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.server.apis.security.GateKeeper;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.insight.ProgramTypeProp;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;

public class ProgramTypeRepository {
			
	private final static String NAMESPACE = DatastoreNamespaces.INSIGHT;
	
	public static List<ProgramTypeProp> getAll() {
		NamespaceManager.set(NAMESPACE);
		
		List<ProgramTypeEntity> entities = ofy().load().type(ProgramTypeEntity.class).list();
		
		List<ProgramTypeProp> props = new ArrayList<ProgramTypeProp>();
		
		for (ProgramTypeEntity entity : entities) {
			props.add(entity.toProp());
		}
		
		return props;
	}
	
	static Key<ProgramTypeEntity> getKeyByName(String name) {
		
		NamespaceManager.set(NAMESPACE);		
		Key<ProgramTypeEntity> key = ofy().load().type(ProgramTypeEntity.class)
				.filter("name", name.toLowerCase()).first().key();
		return key;
	}	
	
	public static ProgramTypeProp get(String name) {
						
		Key<ProgramTypeEntity> key = getKeyByName(name);
		
		if (null == key)
			return null;
		
		NamespaceManager.set(NAMESPACE);
		ProgramTypeEntity entity = ofy().load().key(key).get();
		
		return entity.toProp();		
	}
	
	public static ProgramTypeProp add(String name, String login) {
		
		GateKeeper.ensurePrivilege(login, Privileges.EDIT_PROGRAM_TYPE);
		
		if ((name == null) || (name.equals("")))
			throw new APIException(Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED, 
					"Program type cannot be null or empty string");
		
		if (null != getKeyByName(name))
			throw new APIException(Status.ERROR_RESOURCE_ALREADY_EXISTS, 
				"Program type [" + name + "] already exists");
			
		ProgramTypeEntity entity = new ProgramTypeEntity();
		entity.name = name.toLowerCase();		
		
		NamespaceManager.set(NAMESPACE);
		ofy().save().entity(entity).now();
		
		return entity.toProp();		
	}
	
	public static ProgramTypeProp rename(String newName, String existingName,
			String login) {								
		
		GateKeeper.ensurePrivilege(login, Privileges.EDIT_PROGRAM_TYPE);
		
		if ((newName == null) || (newName.equals("")))
			throw new APIException(Status.ERROR_RESOURCE_INCORRECTLY_SPECIFIED, 
					"New name cannot be null or empty string");
		
		Key<ProgramTypeEntity> key = getKeyByName(existingName);
		
		NamespaceManager.set(NAMESPACE);
		ProgramTypeEntity entity = ofy().load().key(key).get();
				
		entity.name = newName.toLowerCase();
		return entity.toProp();
	}
}
